package com.clear.wechat.handler;

import com.clear.wechat.handler.enums.WechatMSGEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WechatMsgFactory implements InitializingBean {

    @Resource  // 使用该注解可以将如下接口的所有实现类注入到 wechatMsgHandlerList
    private List<WechatMsgHandler> wechatMsgHandlerList;

    private Map<WechatMSGEnum, WechatMsgHandler> handlerMap = new HashMap<>();

    /**
     * 根据消息类型获取对应的handler
     *
     * @param msgType
     * @return
     */
    public WechatMsgHandler getHandlerByMsgType(String msgType) {
        WechatMSGEnum msgEnum = WechatMSGEnum.getByMsgType(msgType);
        return handlerMap.get(msgEnum);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        for (WechatMsgHandler wechatMsgHandler : wechatMsgHandlerList) {
            handlerMap.put(wechatMsgHandler.getMsgType(), wechatMsgHandler);
        }
    }
}
